package com.celesea.workflow.core.service;

import com.celesea.framework.service.AbstractBaseService;
import com.celesea.framework.util.Const;
import com.celesea.framework.util.EnvUtil;
import com.celesea.workflow.core.dao.WorkflowDefineDao;
import com.celesea.workflow.core.entity.WorkflowDefine;
import com.celesea.workflow.core.vo.WorkflowDefineVo;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author JackYuan
 * @create 2017-11-28 12:32
 */
@Service
public class WorkflowDefineServiceImpl extends AbstractBaseService<WorkflowDefine> implements WorkflowDefineService {

    @Autowired
    private WorkflowDefineDao workflowDefineDao;

    @Autowired
    private WorkflowNodeService workflowNodeService;

    @Override
    public void doRemoveMapping(String id) {
        workflowNodeService.doDeleteByDefine(id);
    }

    @Override
    public WorkflowDefineVo insert(WorkflowDefineVo defineVo) {
        defineVo.initStartNodeId(workflowNodeService.generatPk());
        WorkflowDefine entity = super.insert(defineVo);
        defineVo.initNodeRelation(nodes ->
                workflowNodeService.insertByWorkflowDefine(defineVo)
        );
        return defineVo;
    }

    @Override
    public WorkflowDefine findActive(String code) {
        Example example = new Example(WorkflowDefine.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("tenantId", EnvUtil.getTenantId())
                .andEqualTo("code", code)
                .andEqualTo("statusFlag", Const.Bool.TRUE);
        example.orderBy("version").desc();
        List<WorkflowDefine> defines = workflowDefineDao.selectByExample(example);
        Assert.notEmpty(defines, "没有找到有效的流程配置");
        return defines.get(0);
    }
}
